package com.mp3player.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

import com.mp3player.model.Lyric;
import com.mp3player.model.Mp3Info;
import com.mp3player.util.FileUtils;
import com.mp3player.util.MetaData;

import java.util.List;

public class PlayMp3Service extends Service {

    private Mp3Info mp3Info = null;
    private boolean isPlaying = false;
    private boolean isPause = false;
    private MediaPlayer mediaPlayer = null;

    private List<Long> sequentialTimestamp = null;
    private List<String> sequentialLyrics = null;

    private Handler updateLyricHandler = null;
    private long offset = 0l;

    private LyricTimer lyricTimer = null;
    private BroadcastReceiver seekPositionReceiver = null;

    public PlayMp3Service() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //获得传过来的Intent
        if (intent != null) {
            if (MetaData.START_SERVICE == intent.getIntExtra(MetaData.INTENT_CATEGORY, 0)) {
                mp3Info = (Mp3Info) intent.getSerializableExtra(MetaData.MP3_INFO_KEY);

                //加载音乐，准备播放
                mediaPlayer = MediaPlayer.create(PlayMp3Service.this, FileUtils.getMp3Uri(mp3Info));
                try {
                    mediaPlayer.prepare();
                    mediaPlayer.seekTo(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                isPause = true;

                //activity打开即播放mp3
                switchMp3Status();
                updateLyricHandler = new Handler();
                lyricTimer = new LyricTimer();
                updateLyricHandler.postDelayed(lyricTimer, 5L);

                Lyric lyric = new Lyric(MetaData.root.getAbsolutePath()+FileUtils.SEPERATOR+MetaData.SAVE_DIR+mp3Info.getLrcName());
                sequentialTimestamp = lyric.getSequentialTimestamp();
                sequentialLyrics = lyric.getSequentialLyrics();

                //注册一个广播接收器用接收关闭这个播放服务的命令
                IntentFilter intentFilter = new IntentFilter(MetaData.COMMAND_FOR_PLAY_SERVICE_ACTION);
                this.registerReceiver(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        if (MetaData.STOP_SERVICE_COMMAND == intent.getIntExtra(MetaData.STOP_COMMAND_KEY, 0)) {
                            System.out.println("receive stop service command...");
                            updateLyricHandler.removeCallbacks(lyricTimer);
                            mediaPlayer.stop();
                            mediaPlayer.release();
                            PlayMp3Service.this.unregisterReceiver(seekPositionReceiver);
                            PlayMp3Service.this.unregisterReceiver(this);
                            PlayMp3Service.this.stopSelf();
                        }
                    }
                }, intentFilter);

                //注册进度接收器
                IntentFilter i = new IntentFilter(MetaData.SEEK_POSITION_ACTION);
                seekPositionReceiver = new SeekPositionBroadcastReceiver();
                this.registerReceiver(seekPositionReceiver, i);
            }
            if (MetaData.SWITCH_MP3_STATUS == intent.getIntExtra(MetaData.INTENT_CATEGORY, 0)) {
                switchMp3Status();
            }
        }

        return Service.START_NOT_STICKY;
    }

    /**
     * <p>切换播放器状态，或播放mp3，或暂停mp3，并发送这个消息到activity，通知activity更新状态</p>
     * <p>需要保证mp3播放器能够初始化</p>
     */
    private void switchMp3Status() {
        Intent intent = new Intent(MetaData.PLAY_STATUS_ACTION);

        //需要保证mp3播放器能够初始化
        if (mediaPlayer != null) {
            if (!isPlaying) {
                mediaPlayer.start();
                isPlaying = true;
                isPause = false;
                intent.putExtra(MetaData.PLAYING_STATUS_KEY, MetaData.START_PLAYING);
            } else {
                mediaPlayer.pause();
                isPlaying = false;
                isPause = true;
                intent.putExtra(MetaData.PLAYING_STATUS_KEY, MetaData.PAUSE_PLAYING);
            }
            this.sendBroadcast(intent);
        } else {
            Toast.makeText(PlayMp3Service.this, "播放失败", Toast.LENGTH_SHORT).show();
            this.stopSelf();
        }
    }

    class LyricTimer implements Runnable {
        @Override
        public void run() {
            try {
                if (!mediaPlayer.isPlaying()){
                    updateLyricHandler.postDelayed(new LyricTimer(), 200L);
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            offset = mediaPlayer.getCurrentPosition();
            String lastLyric = "";
            String updateLyric = "";
            String nextLyric = "";
            for (int i = 0; i < sequentialTimestamp.size(); i++) {
                if (i < sequentialTimestamp.size()-1) {
                    if (offset > sequentialTimestamp.get(i) && offset <= sequentialTimestamp.get(i + 1)) {
                        if (i == 0) {
                            updateLyric = sequentialLyrics.get(i);
                            nextLyric = sequentialLyrics.get(i + 1);
                        } else if (i > 0) {
                            lastLyric = sequentialLyrics.get(i - 1);
                            updateLyric = sequentialLyrics.get(i);
                            nextLyric = sequentialLyrics.get(i + 1);
                        }
                        break;
                    }
                } else {
                    lastLyric = sequentialLyrics.get(i - 1);
                    updateLyric = sequentialLyrics.get(i);
                }
            }
            //将歌词信息发送出去
            Intent intent = new Intent(MetaData.UPDATE_LYRIC_ACTION);
            intent.putExtra(MetaData.LAST_LYRIC_KEY, lastLyric);
            intent.putExtra(MetaData.UPDATE_LYRIC_KEY, updateLyric);
            intent.putExtra(MetaData.NEXT_LYRIC_KEY, nextLyric);
            PlayMp3Service.this.sendBroadcast(intent);

            //将歌曲的播放总时长和目前播放的时间发送出去
            Intent i = new Intent(MetaData.PLAY_POSITION_ACTION);
            i.putExtra(MetaData.TOTAL_PLAY_TIME_KEY, mediaPlayer.getDuration());
            i.putExtra(MetaData.PLAY_POSITION_KEY, mediaPlayer.getCurrentPosition());
            PlayMp3Service.this.sendBroadcast(i);

            updateLyricHandler.postDelayed(new LyricTimer(), 200L);
        }
    }

    class SeekPositionBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            mediaPlayer.pause();
            mediaPlayer.seekTo(intent.getIntExtra(MetaData.SEEK_POSITION_KEY, 0));
            mediaPlayer.start();
        }
    }

}
